package com.zxjbyte.yiyi.framework.common.domain;

import cn.hutool.core.convert.Convert;
import com.zxjbyte.yiyi.framework.common.util.JsonUtil;
import org.springframework.util.LinkedCaseInsensitiveMap;

import java.util.Map;

/**
 * 链式map
 * @Author zhangxingjia
 * @Date 2023/4/4 11:09
 * @Version: 1.0
 */
public class Kv extends LinkedCaseInsensitiveMap<Object> {
    private static final long serialVersionUID = 1L;

    public static Kv create() {
        return new Kv();
    }

    /**
     * 设置键值对
     * @param key
     * @param value
     * @return
     */
    public Kv set(String key, Object value) {
        this.put(key, value);
        return this;
    }

    /**
     * 设置键值对，当键或值为null时忽略
     * @param key
     * @param value
     * @return
     */
    public Kv setIgnoreNull(String key, Object value) {
        if (key != null && value != null) {
            set(key, value);
        }
        return this;
    }

    /**
     * 设置全部
     */
    public Kv setAll(Map<? extends String, ?> map) {
        if (map != null) {
            this.putAll(map);
        }
        return this;
    }

    public Object getObj(String key) {
        return super.get(key);
    }

    /**
     * 获得特定类型值
     *
     * @param <T>          值类型
     * @param key         字段名
     * @param defaultValue 默认值
     * @return 字段值
     */
    @SuppressWarnings("unchecked")
    public <T> T get(String key, T defaultValue) {
        final Object result = get(key);
        return (T) (result != null ? result : defaultValue);
    }

    /**
     * 获取Json格式字符串
     * @return
     */
    public String toJsonStr(){
        return JsonUtil.toJsonAsString(this);
    }


    /**
     * 获得特定类型值
     *
     * @param attr 字段名
     * @return 字段值
     */
    public String getStr(String attr) {
        return Convert.toStr(get(attr), null);
    }

    public Integer getInt(String attr) {
        return Convert.toInt(get(attr), null);
    }

    public Long getLong(String attr) {
        return Convert.toLong(get(attr), null);
    }

    public Float getFloat(String attr) {
        return Convert.toFloat(get(attr), null);
    }

    public Double getDouble(String attr) {
        return Convert.toDouble(get(attr), null);
    }

    public Boolean getBool(String attr) {
        return Convert.toBool(get(attr), null);
    }

    private Kv() {
        super();
    }

    @Override
    public Kv clone() {
        Kv clone = new Kv();
        clone.putAll(this);
        return clone;
    }
}
